package com.toweave.starter.utils;


import android.content.Context;
import android.util.Log;

import com.toweave.starter.beans.TestBean;
import com.toweave.starter.components.Loading;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

// 这是编程的一个好习惯，称为“针对接口编程，而不是针对实现编程”。
public class RequestUtil {
  public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
  static OkHttpClient client = new OkHttpClient.Builder()
      .readTimeout(1, TimeUnit.SECONDS)   // 设置读取超时时间
      .writeTimeout(1, TimeUnit.SECONDS)  // 设置写入超时时间
      .connectTimeout(1, TimeUnit.SECONDS) // 设置连接超时时间
      .build();

  public static void post(Context ctx, String url, String json, ResponseCallBack callback, boolean showLoading) {
    Loading loading = new Loading(ctx);
    if (showLoading) {
      loading.show();
    }

    RequestBody body = RequestBody.create(json, JSON);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();

    client.newCall(request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        Log.e("-liz-onResponseFailure", String.valueOf(e));
        UiThreadUtil.runOnUiThread(new Runnable() {
          @Override
          public void run() {
            if (showLoading) {
              loading.hide();
            }
            String errMsg = "";
            if (e instanceof SocketTimeoutException) {
              // 处理请求超时
              errMsg = "处理请求超时";
            } else if (e instanceof UnknownHostException) {
              // 处理无网络连接的情况
              errMsg = "网络连接异常";
            } else {
              // 处理其他类型的IOException
              errMsg = "未知错误";
            }
            Log.e("-liz-onResponse Error", errMsg);
            // 在这里更新UI，显示错误消息（注意：需要在主线程上操作）

            // 在这里处理失败情况，更新UI
            callback.onFailure(e);
          }
        });
      }

      @Override
      public void onResponse(Call call, Response response) {
        UiThreadUtil.runOnUiThread(new Runnable() {
          @Override
          public void run() {
            if (showLoading) {
              loading.hide();
            }
            String errMsg = "";
            if (!response.isSuccessful()) {
              // 根据响应码处理客户端或服务器错误
              int statusCode = response.code();
              if (statusCode >= 500) {
                // 服务器错误
                errMsg = "服务端未响应或出错";
              } else if (statusCode >= 405) {
                errMsg = "客户端错误";
              } else if (statusCode == 404) {
                // 客户端错误
                errMsg = "不存在或未发现";
              } else if (statusCode == 403) {
                // 客户端错误
                errMsg = "禁止访问";
              } else if (statusCode == 401) {
                // 客户端错误
                errMsg = "未授权或未登录";
              } else if (statusCode == 400) {
                // 客户端错误
                errMsg = "请求错误";
              }
              Log.e("-liz-onResponse Error", statusCode + errMsg);
              // 注意：需要关闭响应体
              if (response.body() != null) {
                response.body().close();
              }
              return;
            }
            // 在这里处理响应，更新UI
            try {
              if (response.body() != null) {
                String s = response.body().string();
                Log.d("-liz-onResponse", "onResponse: " + s);
                TestBean t = FastJsonUtil.JsonStringToObject(s, TestBean.class);
                // t = FastJsonUtil.JsonStringToList(s, TestBean.class);
                callback.onResponse(t); // 通过回调传递响应
              } else {
                callback.onResponse(null); //
              }
              // // 注意：需要关闭响应体
              // response.body().close();
            } catch (IOException e) {
              Log.e("-liz-onResponse Error", String.valueOf(e));
              throw new RuntimeException(e);
            } finally {
              // 无论如何，确保关闭响应体
              if (response.body() != null) {
                response.body().close();
              }
            }

          }
        });

      }
    });
  }

  // post 请求不使用 loading, 需要主动设置 loading 的值为 false
  public static void postAsync(Context ctx, String url, String json, ResponseCallBack callback, boolean showLoading) {
    post(ctx, url, json, callback, showLoading);
  }

  // 默认 post 请求使用 loading
  public static void postAsync(Context ctx, String url, String json, ResponseCallBack callback) {
    boolean showLoading = true;
    post(ctx, url, json, callback, showLoading);
  }


}
